﻿var map, lyrvietnam, lonlat;
var markLayer;
var drag;
var selectControl, selectedFeatures, lastPixel;

var idShopEdit; //bien toan cuc nay dung de luu id cua shop dung cho edit
var idFeatureDelete; //bien toan cuc luu thong tin de delete diem
var boolEdit = false;
var dialog;

 //ham khoi tao 
function init(tentinh,nen,thuy_he,dan_cu,giao_thong,dia_hinh,danh_gioi) {
        var bounds = new OpenLayers.Bounds(573839.202, 2311109.821, 606329.848, 2366319.978);
        var options = {
            controls: [],     
            maxExtent: bounds,
            maxResolution: bounds,
            projection: "EPSG:3406",
            fractionalZoom: true,
            singleTile: true,
            ratio: 1,
            units: 'm'               
        };
        lyrvietnam = new OpenLayers.Layer.WMS(tentinh, "http://www.lifetimetech.vn:8383/geoserver/wms", { 'layers':nen, transparent: true, format: 'image/png' }, { singleTile: true, isBaseLayer: true, transitionEffect: 'resize' });
        map = new OpenLayers.Map('map', {
            controls: [
                    new OpenLayers.Control.PanZoomBar(),
                    new OpenLayers.Control.LayerSwitcher(),
                    new OpenLayers.Control.OverviewMap({ maximized: true }),
                    new OpenLayers.Control.Navigation({               
                                type: OpenLayers.Control.TYPE_TOGGLE,
                                zoomWheelEnabled: true,
                                mouseWheelOptions: { interval: 1, cumulative: false } 
                    }),
                ],numZoomLevels: 22
        }, options);
          
            
        var nt_hanoi_th = new OpenLayers.Layer.WMS(
		    "Thuy he",
		    "http://www.lifetimetech.vn:8383/geoserver/wms",
		    {
			    layers: thuy_he,
			    transparent: "true",
			    format: "image/png"
		    },
		    {
			    isBaseLayer: false,
			    visibility : false,
		    });
	    map.addLayer(nt_hanoi_th);
					
	    var nt_hanoi_dc = new OpenLayers.Layer.WMS(
		    "Dan cu",
		    "http://www.lifetimetech.vn:8383/geoserver/wms",
		    {
			    layers: dan_cu,
			    transparent: "true",
			    format: "image/png"
		    },
		    {
			    isBaseLayer: false,
			    visibility : false,
		    });
	    map.addLayer(nt_hanoi_dc);
			
	    var nt_hanoi_gt = new OpenLayers.Layer.WMS(
		    "Giao thong",
		    "http://www.lifetimetech.vn:8383/geoserver/wms",
		    {
			    layers: giao_thong,
			    transparent: "true",
			    format: "image/png"
		    },
		    {
			    isBaseLayer: false,
			    visibility : false,
		    });
	    map.addLayer(nt_hanoi_gt);
			
	    var nt_hanoi_dh = new OpenLayers.Layer.WMS(
		    "Dia hinh",
		    "http://www.lifetimetech.vn:8383/geoserver/wms",
		    {
			    layers: dia_hinh,
			    transparent: "true",
			    format: "image/png"
		    },
		    {
			    isBaseLayer: false,
			    visibility : false,
		    });
	    map.addLayer(nt_hanoi_dh);
             
        var nt_hanoi_rg = new OpenLayers.Layer.WMS(
		    "Ranh gioi",
		    "http://www.lifetimetech.vn:8383/geoserver/wms",
		    {
			    layers: danh_gioi,
			    transparent: "true",
			    format: "image/png"
		    },
		    {
			    isBaseLayer: false,
			    visibility : false,
		    });
	    map.addLayer(nt_hanoi_rg);

        map.addLayer(lyrvietnam);
        map.addControl(new OpenLayers.Control.LayerSwitcher());
        map.addControl(new OpenLayers.Control.MousePosition({ element: $('location') }));
        map.addControl(new OpenLayers.Control.OverviewMap({ maximized: true }));
        //map.setCenter(new OpenLayers.LonLat(111.84197918135, 21.027580898957),20);
       // map.zoomToScale(400000,true);
       // map.zoomIn();
           
        markLayer = new OpenLayers.Layer.Vector("PCB");
        map.addLayer(markLayer);

        markLayer.div.oncontextmenu = function noContextMenu(e) {
            if (OpenLayers.Event.isRightClick(e)) {
                    if (boolEdit) {
                     dialog.dialog("destroy").remove();    
                    var left = (screen.width / 2) - (400 / 2);
                    var top = (screen.height / 2) - (500 / 2);
                    var myWindown = window.open('Default2.aspx?id=' + idShopEdit + '&place_id=' + id_place , "my windown", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + 400 + ', height=' + 500 + ', top=' + top + ', left=' + left);                                                
                }             
            }
            return false; 
        };

        

        loadShopMapFromDataBase();
            

        var click = new OpenLayers.Control.Click();//su kien click chuot vao ban phim
        map.addControl(click);
        click.activate();

           
        var selectControl = new OpenLayers.Control.SelectFeature(
        markLayer, {
            hover: true,
            highlightOnly: true,
            renderIntent: "temporary",
            eventListeners: {
                featurehighlighted: onSelect,
                featureunhighlighted: onUnselect
            }
        });

        map.addControl(selectControl);
        selectControl.activate();    
        selectedFeatures = new Array();

        drag = new OpenLayers.Control.DragFeature(markLayer, {
            onStart: startDrag,
            onDrag: doDrag,
            onComplete: endDrag,
            onEnter: onEnter,
            onLeave: onLeave
        });

        map.addControl(drag);

}     
 /*Feature enter */
function onEnter(feature) {
    scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		scrOfY = window.pageYOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		scrOfY = document.body.scrollTop; 
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		scrOfY = document.documentElement.scrollTop;
	}    
    var lonlat = new OpenLayers.LonLat(feature.x, feature.y);
    var pixxel = map.getPixelFromLonLat(lonlat);
    var ypixel = pixxel.y;
    if(ypixel > 320 + scrOfY)
    {
        ypixel = -(20-scrOfY);
    }
    boolEdit = true;
    idShopEdit = feature.geometry.id;
    idFeatureDelete = feature.id;
    dialog = $("<div>" + feature.geometry.outerHtml + "</div>").dialog({ title: feature.geometry.tagName, position: [pixxel.x +20,ypixel + 170 - scrOfY] });
}
/*Feature leave */
function onLeave(feature) {
    boolEdit = false;
    dialog.dialog("destroy").remove();
    idShopEdit = feature.geometry.id;
    idFeatureDelete = feature.id;
}
/* Feature starting to move */
function startDrag(feature, pixel) {
    lastPixel = pixel;
    dialog.dialog("destroy").remove();
}
/* Feature moving */
function doDrag(feature, pixel) {
    for (f in selectedFeatures) {
        if (feature == selectedFeatures[f]) {
            var res = map.getResolution();
            selectedFeatures[f].geometry.move(res * (pixel.x - lastPixel.x), res * (lastPixel.y - pixel.y));
            markLayer.drawFeature(selectedFeatures[f]);
        }
    }
    lastPixel = pixel;
}
/* Feature stopped moving */
function endDrag(feature, pixel) {
    for (f in selectedFeatures) {
        f.state = OpenLayers.State.UPDATE;
    }
    saveShop(feature.geometry.id, feature.geometry.getBounds().getCenterLonLat().lon, feature.geometry.getBounds().getCenterLonLat().lat);
}

function onSelect(feature) {
   selectedFeatures.push(feature);
   drag.activate();  
 }

function onUnselect(feature) {
    for (f in selectedFeatures) {
           selectedFeatures.pop();
    }
}
//su kien chuot
OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
    defaultHandlerOptions: {
        'single': true,
        'dblclick': false,
        'pixelTolerance': 0,
        'stopSingle': false,
        'stopDouble': false
    },

    initialize: function (options) {
        this.handlerOptions = OpenLayers.Util.extend(
                        {}, this.defaultHandlerOptions
                    );
        OpenLayers.Control.prototype.initialize.apply(
                        this, arguments
                    );
        this.handler = new OpenLayers.Handler.Click(
                        this, {
                            'click': this.singleClick
                        }, this.handlerOptions
                    );
    },

    singleClick: function (e) {
        lonlat = map.getLonLatFromPixel(e.xy);
        showPopup(lonlat.lat, lonlat.lon);
    }

});

function deleteFeature() {
    markLayer.removeFeatures(markLayer.getFeatureById(idFeatureDelete));
    drag.deactivate();
}

function saveShop(_id, _xlon, _ylat) {
    $.ajax({
        type: "POST",
        url: "Default.aspx/saveShopAffterMove",
        data: "{id: '" + _id + "',x: '" + _xlon + "',y: '" + _ylat + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: alert('move success ^^!')
    });
}

function loadShopMapFromDataBase() {
    $.ajax({
        type: "POST",
        url: "Default.aspx/getListShopMapFromDataBase",
        contentType: "application/json; charset=utf-8",
        data: "{place_id: '" + id_place + "'}",
        dataType: "json",
        success: function (response) {
            var shops = response.d;
            $.each(shops, function (index, ShopMap) {
                var feature = new OpenLayers.Feature.Vector(
                        new OpenLayers.Geometry.Point(ShopMap.x, ShopMap.y),
                        { some: 'data' },
                        { externalGraphic: "http://www.openlayers.org/dev/img/marker.png", graphicHeight: 21, graphicWidth: 25 });
                feature.geometry.id = ShopMap.id;
                feature.geometry.outerHtml = "<table style='width:100%' border='1px' bordercolor='#c3c3c3' bordercolordark='#FF3300' cellspacing='0px' cellpadding='2px' bordercolorlight='#FF3300'>"
                            + "<tr><td width='40%'>Name</td><td width='60%'>"
                            + ShopMap.name + "</td></tr><tr><td>Description</td><td>"
                            + ShopMap.description + "</td></tr><tr><td>Address</td><td>"
                            + ShopMap.address + "</td></tr><tr><td>Tell</td><td>"
                            + ShopMap.tell + "</td></tr><tr><td>Phone</td><td>"
                            + ShopMap.phone + "</td></tr><tr><td>Image</td><td>"
                            + ShopMap.image + "</td></tr></table>";
                feature.geometry.tagName = "<p>" + ShopMap.name + "<\p>";
                feature.x = ShopMap.x;
                feature.y = ShopMap.y;
                markLayer.addFeatures(feature);
            });
        },
        error: AjaxFailed
    });
}

function AjaxSucceeded(result) {
    alert(result.d);
}

function AjaxFailed(result) {
    alert(result.status + ' ' + result.statusText);
}

function updateAfterEdit() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{id: '" + idShopEdit + "'}",
        url: "Default.aspx/getShopMapFromDataBaseId",
        dataType: "json",
        success: function (data) {
            var ShopMap = data.d;
            markLayer.getFeatureById(idFeatureDelete).geometry.outerHtml = "<table style='width:100%' border='1px' bordercolor='#c3c3c3' bordercolordark='#FF3300' cellspacing='0px' cellpadding='2px' bordercolorlight='#FF3300'>"
                            + "<tr><td width='40%'>Name</td><td width='60%'>"
                            + ShopMap.name + "</td></tr><tr><td>Description</td><td>"
                            + ShopMap.description + "</td></tr><tr><td>Address</td><td>"
                            + ShopMap.address + "</td></tr><tr><td>Tell</td><td>"
                            + ShopMap.tell + "</td></tr><tr><td>Phone</td><td>"
                            + ShopMap.phone + "</td></tr><tr><td>Image</td><td>"
                            + ShopMap.image + "</td></tr></table>";
            markLayer.getFeatureById(idFeatureDelete).geometry.tagName = "<p>" + ShopMap.name + "<\p>";
            markLayer.getFeatureById(idFeatureDelete).x = ShopMap.x;
            markLayer.getFeatureById(idFeatureDelete).y = ShopMap.y;
        }
    });
}

function showPopup(x, y) {
    var left = (screen.width / 2) - (400 / 2);
    var top = (screen.height / 2) - (500 / 2);
    var myWindown = window.open('shop.aspx?x=' + x + '&y=' + y + '&place_id=' + id_place , "my windown", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + 400 + ', height=' + 500 + ', top=' + top + ', left=' + left);
}

function addMakerPopup() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        url: "Default.aspx/getShopMapHaveIdMax",
        dataType: "json",
        success: function (data) {
            var ShopMap = data.d;
            var feature = new OpenLayers.Feature.Vector(
                    new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat),
                    { some: 'data' },
                     { externalGraphic: "http://www.openlayers.org/dev/img/marker.png", graphicHeight: 21, graphicWidth: 25 });
            feature.geometry.id = ShopMap.id;
            feature.geometry.outerHtml = "<table style='width:100%' border='1px' bordercolor='#c3c3c3' bordercolordark='#FF3300' cellspacing='0px' cellpadding='2px' bordercolorlight='#FF3300'>"
                            + "<tr><td width='40%'>Name</td><td width='60%'>"
                            + ShopMap.name + "</td></tr><tr><td>Description</td><td>"
                            + ShopMap.description + "</td></tr><tr><td>Address</td><td>"
                            + ShopMap.address + "</td></tr><tr><td>Tell</td><td>"
                            + ShopMap.tell + "</td></tr><tr><td>Phone</td><td>"
                            + ShopMap.phone + "</td></tr><tr><td>Image</td><td>"
                            + ShopMap.image + "</td></tr></table>";
            feature.geometry.tagName = "<p>" + ShopMap.name + "<\p>";
            feature.x = ShopMap.x;
            feature.y = ShopMap.y;
            markLayer.addFeatures(feature);
        }
    });
}